package com.size.mall.interceptors;

import com.alibaba.fastjson.JSON;
import com.size.mall.config.annotations.LoginRequired;
import com.size.mall.util.CookieUtil;
import com.size.mall.util.HttpclientUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static cn.hutool.core.util.StrUtil.isBlank;
import static cn.hutool.core.util.StrUtil.isNotBlank;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 拦截器代码


        // 判断被拦截的请求的访问的方法的注解

        HandlerMethod hm = (HandlerMethod) handler;
        LoginRequired methodAnnotation = hm.getMethodAnnotation(LoginRequired.class);


        //region 没有登陆注解,直接放行
        if (methodAnnotation == null) {
            return true;
        }
        //endregion


        //region 新旧token检查
        String token = "";

        Cookie[] cookies = request.getCookies();
        String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);

        if (isNotBlank(oldToken)) {
            token = oldToken;
        }

        String newToken = request.getParameter("token");
        if (isNotBlank(newToken)) {
            token = newToken;
        }
        //endregion


        // 是否必须登陆成功
        boolean loginSuccess = methodAnnotation.loginSuccess();


        String state = "fail";
        Map<String, String> stateMap = new HashMap<>();
        

        if (isNotBlank(token)) {

            //region 获取客户端的ip  越过nginx
            String ip = request.getHeader("x-forwarded-for"); // nginx 的负载的客户ip
            if (isBlank(ip)) {
                // 没有就是客户机直接访问
                ip = request.getRemoteAddr();
                if (isBlank(ip)) {
                    // 再没有给默认ip
                    ip = "127.0.0.1";

                }
            }
            //endregion

            // 调用认证中心进行认中心

            String stateJson = HttpclientUtil.doGet("http://yin:9040/verify?token=" + token + "&currentIp=" + ip);
            stateMap = JSON.parseObject(stateJson, Map.class);
            state = stateMap.get("status");
        }


        if (loginSuccess) {
            // 必须登陆成功才能使用
            if (!state.equals("success")) {

                StringBuffer requestURL = request.getRequestURL();


                String returnUrl = Optional.ofNullable((String) request.getParameter("returnUrl")).orElse("http://yin:8060/index");


                // 踢回登陆界面,附原始访问地址
                response.sendRedirect("http://yin:9040/index?returnUrl=" + returnUrl);
                return false;


            } else {
                // 验证通过, 覆盖cookie中的token
                request.setAttribute("memberId", stateMap.get("memberId"));
                request.setAttribute("nickname", stateMap.get("nickname"));
                if (isNotBlank(token)) {
                    CookieUtil.setCookie(request, response, "oldToken", token, 60 * 60 * 2, true);
                }
            }


        } else {
            // 没有登陆也能用 , 但是必须验证
            if (state.equals("success")) {
                // 需要将token携带的用户信息写入
                request.setAttribute("memberId", stateMap.get("memberId"));
                request.setAttribute("nickname", stateMap.get("nickname"));
            }

            if (isNotBlank(token)) {
                CookieUtil.setCookie(request, response, "oldToken", token, 60 * 60 * 2, true);
            }

        }


        System.out.println("进入拦截器方法");
        // return super.preHandle(request, response, handler);
        return true;
    }

}
